<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时日志显示</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }

        .log-item {
            transition: all 0.3s ease;
            flex: 1 1 calc(50% - 0.5rem); /* 两列布局，考虑间距 */
            min-width: calc(50% - 0.5rem);
        }

        .log-item:hover {
            transform: scale(1.02);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        @media (max-width: 768px) {
            .log-item {
                flex: 1 1 100%; /* 小屏幕单列布局 */
                min-width: 100%;
            }
        }
    </style>
</head>

<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4 md:p-8">
<div class="max-w-6xl w-full bg-white rounded-lg shadow-lg overflow-hidden">
    <div class="bg-blue-600 text-white p-4 md:p-6 flex justify-between items-center">
        <h1 class="text-xl md:text-3xl font-bold">实时日志 <i class="fa fa-spinner fa-spin ml-2"></i></h1>
        <button id="clear-logs" class="bg-white text-blue-600 py-1 px-3 md:py-2 md:px-4 rounded-md hover:bg-gray-100 focus:outline-none">
            清空日志
        </button>
    </div>
    <div id="log-container" class="p-4 md:p-6 h-[32rem] overflow-y-auto flex flex-wrap gap-2">
        <!-- 日志信息将显示在这里 -->
    </div>
</div>
<script>
    const socket = new WebSocket('ws://localhost:9090/ws');
    const logContainer = document.getElementById('log-container');
    const clearLogsButton = document.getElementById('clear-logs');
    const LOG_KEY = 'logMessages';

    // 页面加载时从本地存储读取日志
    function loadLogsFromStorage() {
        const storedLogs = localStorage.getItem(LOG_KEY);
        if (storedLogs) {
            const logs = JSON.parse(storedLogs);
            logs.reverse().forEach(log => {
                const logMessage = createLogMessageElement(log);
                logContainer.appendChild(logMessage);
            });
            logContainer.scrollTop = 0;
        }
    }

    function createLogMessageElement(logData) {
        const statusColor = (logData.status === 200||logData.status === 302) ? 'text-green-600' : 'text-red-600';

        const html = `
            <div class="log-item bg-gray-100 p-2 rounded-md flex flex-col space-y-2">
                <p class="font-bold text-gray-800 text-lg">时间: <span class="font-normal text-base">${logData.time || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg">方法: <span class="font-normal text-base">${logData.method || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg ${statusColor}">状态: <span class="font-normal text-base">${logData.status || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg">延迟: <span class="font-normal text-base">${logData.latency || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg">客户端 IP: <span class="font-normal text-base">${logData.client_ip || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg">客户端ID: <span class="font-normal text-base">${logData.client_id || 'N/A'}</span></p>
                <p class="font-bold text-gray-800 text-lg">请求 URI: <span class="font-normal text-base truncate">${logData.request_uri || 'N/A'}</span></p>
            </div>
        `;

        const template = document.createElement('template');
        template.innerHTML = html.trim();
        return template.content.firstChild;
    }

    // 保存日志到本地存储
    function saveLogToStorage(logData) {
        const storedLogs = localStorage.getItem(LOG_KEY);
        let logs = storedLogs ? JSON.parse(storedLogs) : [];
        logs.unshift(logData);
        // 限制存储的日志数量，避免占用过多空间
        if (logs.length > 100) logs = logs.slice(0, 100);
        localStorage.setItem(LOG_KEY, JSON.stringify(logs));
    }

    // 清空日志
    function clearLogs() {
        logContainer.innerHTML = '';
        localStorage.removeItem(LOG_KEY);
    }

    socket.onopen = function () {
        console.log('WebSocket 连接已建立');
    };

    socket.onmessage = function (event) {
        try {
            const logData = JSON.parse(event.data);
            const logMessage = createLogMessageElement(logData);
            logContainer.insertBefore(logMessage, logContainer.firstChild);
            saveLogToStorage(logData);
        } catch (error) {
            console.error('解析日志数据时出错:', error);
            const errorMessage = document.createElement('div');
            errorMessage.className = 'log-item bg-red-50 p-4 rounded-md';
            errorMessage.innerHTML = `<p class="font-bold text-lg">错误: <span class="font-normal">解析日志数据时出错: ${event.data}</span></p>`;
            logContainer.insertBefore(errorMessage, logContainer.firstChild);
        }
    };

    socket.onclose = function () {
        console.log('WebSocket 连接已关闭');
        // 可以添加重连逻辑
    };

    // 绑定清空日志按钮事件
    clearLogsButton.addEventListener('click', clearLogs);

    // 页面加载时加载日志
    loadLogsFromStorage();
</script>
</body>
</html>
